﻿using System;
using System.Collections.Generic;
using HK.Core.Common.Data;
using HK.Core.Common.Protocol.Data;
using HK.Core.Utils;
using HK.Editor.GUIEx.Protocol.Data;
using UnityEngine;

namespace HK.Editor.GUIEx.Data
{
    /// <summary>
    /// 白名单窗体数据
    /// </summary>
    [Serializable]
    public class WhiteListWindowData : JsonData<WhiteListWindowData>, IWhiteListWindowData
    {
        /// <summary>
        /// 负载Tag
        /// </summary>
        public string PayloadTag => GetType().Name;

        /// <summary>
        /// 白名单
        /// </summary>
        public IWhiteList List { get; private set; } = null;

        /// <summary>
        /// 重置白名单
        /// </summary>
        /// <param name="iList">白名单</param>
        public void ResetWhiteList(IWhiteList iList)
        {
            if(null == iList || !iList.Valid) return;
            if (null == List)
            {
                List = iList;
            }
            else
            {
                List.ApplyData(iList);
            }
        }

        /// <summary>
        /// 是否包含在白名单中
        /// </summary>
        /// <param name="iTarget">目标</param>
        /// <returns>true:包含; false:不包含;</returns>
        public bool Contains(string iTarget) => List?.Contains(iTarget) ?? false;

        /// <summary>
        /// 追加目标对象
        /// <para>* 无效的目标对象，或者未通过过滤验证的，都将视为失败</para>
        /// </summary>
        /// <param name="iTarget">目标对象</param>
        /// <returns>true:追加成功; false:追加失败;</returns>
        public bool AddTarget(string iTarget) => List?.AddTarget(iTarget) ?? false;

        /// <summary>
        /// 追加目标对象
        /// <para>* 无效的目标对象，或者未通过过滤验证的，都将视为失败</para>
        /// </summary>
        /// <param name="iTargets">目标对象</param>
        /// <returns>成功追加数量(-1:白名单尚未初始化)</returns>
        public int AddTargets(IReadOnlyList<string> iTargets) => List?.AddTargets(iTargets) ?? -1;

        /// <summary>
        /// 应用数据
        /// </summary>
        /// <param name="iData">数据</param>
        /// <param name="iImport">导入标志位(true:从相应的*.json文件导入; false:反之;)</param>
        /// <returns>true:有变更; false:无变更;</returns>
        public override bool ApplyData(IJsonData iData, bool iImport = false)
        {
            if (null == iData || !iData.Valid) return false;

            var dirty = base.ApplyData(iData, iImport);
            if (dirty && !iImport)
            {
                Dirty = true;
            }

            if (iData is IWhiteListWindowData whiteList)
            {
                dirty = List.ApplyData(whiteList.List);
                if (dirty && !iImport)
                {
                    Dirty = true;
                }
            }

            return Dirty;
        }

        /// <summary>
        /// 清空
        /// </summary>
        public override void Clear()
        {
            base.Clear();
            
            List?.Clear();
        }
        
    }
}
